package com.atguigu.exam.controller;

import com.atguigu.exam.assistant.XiaozhiAgentMCP;
import com.atguigu.exam.entity.ChatForm;
import com.atguigu.exam.service.BannerService;
import com.atguigu.exam.tools.AppointmentTools;
import com.atguigu.exam.tools.BailianTool;
import dev.langchain4j.community.model.dashscope.QwenChatModel;
import dev.langchain4j.community.model.dashscope.QwenStreamingChatModel;
import dev.langchain4j.memory.chat.ChatMemoryProvider;
import dev.langchain4j.rag.content.retriever.ContentRetriever;
import dev.langchain4j.service.AiServices;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 网站的ai聊天客服控制器
 * 包括ai问答、算术题拍照等功能
 */
@RestController
@RequestMapping("/api/ai")
@CrossOrigin
@Tag(name = "ai客服", description = "ai问答、收集网站意见、拍照批阅算术题等功能")
public class XiaozhiMCPV2Controller {

    @Autowired
    private QwenStreamingChatModel qwenStreamingChatModel;

    @Autowired
    private QwenChatModel qwenChatModel;

    @Autowired
    private ChatMemoryProvider chatMemoryProviderXiaozhi;

    @Autowired
    private AppointmentTools appointmentTools;

    @Autowired
    private ContentRetriever contentRetrieverXiaozhiPincone;

    @Autowired
    private BailianTool bailianTool;

    @Autowired
    private BannerService bannerService;


    // 非流式接口 - 用于Knife4j测试
    @Operation(summary = "AI对话(支持图片)", description = "与AI客服进行对话，可上传图片进行批改")
    @PostMapping(value = "/chat-with-image")
    public com.atguigu.exam.common.Result<String> chatWithImage(
            @RequestParam("memoryId") Long memoryId,
            @RequestParam("message") String message,
            @RequestParam(value = "image", required = false) MultipartFile image) {
        try {
            String imageUrl = null;
            // 如果有图片，先上传获取URL
            if (image != null && !image.isEmpty()) {
                // 复用BannerService的上传逻辑
                imageUrl = bannerService.uploadImage(image);
            }

            // 创建包含图片URL的消息
            String finalMessage = imageUrl != null ?
                    message + " [图片地址:" + imageUrl + "]" : message;

            XiaozhiAgentMCP xiaozhiAgentMCP = createNonStreamingAgent();
            String response = xiaozhiAgentMCP.chat(memoryId, finalMessage);
            return com.atguigu.exam.common.Result.success(response);
        } catch (Exception e) {
            return com.atguigu.exam.common.Result.error("AI服务暂时不可用: " + e.getMessage());
        }
    }

    // 流式接口 - 用于前端实时体验
//    @Operation(summary = "AI流式对话", description = "与AI客服进行流式对话（实时响应）")
//    @PostMapping(value = "/chat-stream", produces = MediaType.TEXT_EVENT_STREAM_VALUE)
//    public Flux<String> chatStream(@RequestBody ChatForm chatForm) {
//        XiaozhiAgentMCP xiaozhiAgentMCP = createStreamingAgent();
//        return xiaozhiAgentMCP.chat(chatForm.getMemoryId(), chatForm.getMessage());
//    }



    private XiaozhiAgentMCP createNonStreamingAgent() {
        return AiServices.builder(XiaozhiAgentMCP.class)
                .chatLanguageModel(qwenChatModel) // 非流式模型
                .chatMemoryProvider(chatMemoryProviderXiaozhi)
                .tools(appointmentTools, bailianTool )
                .contentRetriever(contentRetrieverXiaozhiPincone)
                .build();
    }


////    用于前端的实时体验的流式输出Agent
//    private XiaozhiAgentMCP createStreamingAgent() {
//        return AiServices.builder(XiaozhiAgentMCP.class)
//                .streamingChatLanguageModel(qwenStreamingChatModel) // 流式模型
//                .chatMemoryProvider(chatMemoryProviderXiaozhi)
//                .tools(appointmentTools, bailianTool)
//                .contentRetriever(contentRetrieverXiaozhiPincone)
//                .build();
//    }


}